package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.BkArticle;
import com.ruoyi.system.mapper.BkArticleMapper;
import com.ruoyi.system.service.IBkAIService;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class BkAIServiceImpl implements IBkAIService {

    private static final Logger log = LoggerFactory.getLogger(BkAIServiceImpl.class);

    @Autowired
    private BkArticleMapper bkArticleMapper;

    @Value("${ai.deepseek.api-key}")
    private String apiKey;

    @Value("${ai.deepseek.api-url}")
    private String apiUrl;

    @Override
    public String generateArticleExcerpt(String content, String title) {
        try {
            JSONObject requestJson = buildRequest(content, title, "","summary");
            String response = sendRequestToDeepseek(requestJson.toString());
            return parseDeepseekResponse(response);
        } catch (Exception e) {
            log.error("生成摘要失败 | 内容长度:{} | 标题:{} | 错误:{}",
                    content.length(), title, e.getMessage());
            throw new RuntimeException("生成摘要失败: " + e.getMessage());
        }
    }

    @Override
    public List<String> getArticleOptimizationSuggestions(String content, String title, String excerpt) {
        try {
            JSONObject requestJson = buildRequest(content, title, excerpt, "optimization");
            String response = sendRequestToDeepseek(requestJson.toString());
            return processSuggestions(parseDeepseekResponse(response));
        } catch (Exception e) {
            log.error("获取建议失败 | 内容长度:{} | 标题:{} | 错误:{}",
                    content.length(), title, e.getMessage());
            throw new RuntimeException("获取优化建议失败: " + e.getMessage());
        }
    }

    private JSONObject buildRequest(String content, String title, String excerpt, String type) {
        JSONObject requestJson = new JSONObject();
        requestJson.put("model", "deepseek-chat");

        JSONArray messages = new JSONArray();
        JSONObject systemMessage = new JSONObject();
        systemMessage.put("role", "system");

        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user");

        if ("summary".equals(type)) {
            systemMessage.put("content", "你是一个专业的文章摘要生成助手。请根据提供的文章内容生成一个简洁明了的摘要，不超过150字。摘要应该概括文章的核心内容和主要观点，不要包含个人意见或评论。");
            userMessage.put("content", "请为以下标题为《" + title + "》的文章生成一个简洁的摘要：\n\n" + content);
            requestJson.put("temperature", 0.3);
            requestJson.put("max_tokens", 5000);
        } else {
            systemMessage.put("content", "你是一个专业的文章编辑助手。请分析提供的文章内容，给出具体的优化建议。建议应该包括标题优化、内容组织、表达方式、语法错误等方面。请给出不大于10条的具体的优化建议（只需要建议内容）。如果文章很不错，请输出阅读体验。");
            userMessage.put("content", "请分析以下文章：\n标题：《" + title + "》\n"
                    + "简介：" + excerpt + "\n"
                    + "正文内容：\n" + content);
            requestJson.put("temperature", 0.7);
            requestJson.put("max_tokens", 5000);
        }

        messages.add(systemMessage);
        messages.add(userMessage);
        requestJson.put("messages", messages);

        return requestJson;
    }

    private String parseDeepseekResponse(String response) {
        // 基础校验
        if (StringUtils.isEmpty(response)) {
            throw new RuntimeException("API返回空响应");
        }

        // 解析JSON
        JSONObject responseJson;
        try {
            responseJson = JSONObject.parseObject(response);
        } catch (Exception e) {
            log.error("响应解析异常 | 原始响应:{}", response);
            throw new RuntimeException("响应解析失败: " + e.getMessage());
        }

        // 错误处理
        if (responseJson.containsKey("error")) {
            JSONObject error = responseJson.getJSONObject("error");
            String errorMsg = String.format("API错误[%s]: %s",
                    error.getString("code"),
                    error.getString("message"));
            throw new RuntimeException(errorMsg);
        }

        // 数据提取
        JSONArray choices = responseJson.getJSONArray("choices");
        if (choices == null || choices.isEmpty()) {
            throw new RuntimeException("API返回数据格式异常，缺少choices字段");
        }

        try {
            JSONObject firstChoice = choices.getJSONObject(0);
            JSONObject message = firstChoice.getJSONObject("message");
            return message.getString("content").trim();
        } catch (Exception e) {
            log.error("内容提取失败 | 响应结构:{}", responseJson.toJSONString());
            throw new RuntimeException("解析响应内容失败: " + e.getMessage());
        }
    }

    private String sendRequestToDeepseek(String requestBody) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(apiUrl);

        // 增加字符编码设置
        httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
        httpPost.setHeader("Authorization", "Bearer " + apiKey);

        try {
            // 使用UTF-8编码实体
            StringEntity entity = new StringEntity(requestBody, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 增加响应内容长度校验
                if (response.getEntity().getContentLength() == 0) {
                    throw new RuntimeException("API返回空响应");
                }

                String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

                // 记录原始响应（调试用）
                log.debug("原始API响应: {}", responseBody);

                return responseBody;
            }
        } catch (Exception e) {
            // 增加请求体记录
            log.error("失败请求体内容:\n{}", requestBody);
            throw new RuntimeException("API调用失败: " + e.getMessage());
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                log.error("关闭HTTP客户端失败", e);
            }
        }
    }

    @Override
    public boolean updateArticleAIExcerpt(Long articleId, String aiExcerpt) {
        try {
            BkArticle article = new BkArticle();
            article.setId(articleId);
            article.setAiExcerpt(aiExcerpt);
            return bkArticleMapper.updateBkArticle(article) > 0;
        } catch (Exception e) {
            log.error("更新摘要失败 | 文章ID:{} | 摘要:{}", articleId, aiExcerpt, e);
            return false;
        }
    }

    private List<String> processSuggestions(String suggestionsText) {
        List<String> suggestions = new ArrayList<>();
        String[] lines = suggestionsText.split("\n");
        StringBuilder current = new StringBuilder();

        for (String line : lines) {
            if (line.trim().isEmpty()) continue;

            if (line.matches("^(\\d+[\\.、]|[-•*])\\s.*")) {
                if (current.length() > 0) {
                    suggestions.add(current.toString().trim());
                    current.setLength(0);
                }
                current.append(line.replaceAll("^[\\d\\-•*、.\\s]+", "").trim());
            } else {
                current.append(" ").append(line.trim());
            }
        }

        if (current.length() > 0) {
            suggestions.add(current.toString().trim());
        }

        return suggestions.isEmpty() ?
                new ArrayList<String>() {{ add("AI未提供具体建议"); }} :
                suggestions;
    }
}